package 重温_Java并发基础.code.master_worker;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * @author idea
 * @data 2020/2/15
 */
public class Master {

    protected Queue<Object> workerQueue = new ConcurrentLinkedDeque<>();

    protected Map<String, Thread> threadMap = new HashMap<>();

    protected Map<String, Object> resultMap = new ConcurrentHashMap<>();

    public Master(Worker worker, int countWorker){
        worker.setWorkerQueue(workerQueue);
        worker.setResultMap(resultMap);
        for(int i=0;i<countWorker;i++){
            threadMap.put(Integer.toString(i),new Thread(worker,"worker"+i));
        }
    }

    public boolean isComplete(){
        for(String key:threadMap.keySet()){
            if(threadMap.get(key).getState()!=Thread.State.TERMINATED){
                return false;
            }
        }
        return true;
    }

    public void submit(Object job){
        workerQueue.add(job);
    }

    /**
     * 执行任务
     */
    public void execute(){
        for (Map.Entry<String,Thread> stringThreadEntry : threadMap.entrySet()) {
            stringThreadEntry.getValue().start();
        }
    }


}
